<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@include file="/jsp/comm_css_include.jsp"%>
<link href="${basePath}/css/plugins/jqgriddemo/css/ui.jqgrid-bootstrap.min.css" rel="stylesheet" />
<link href="${basePath}/js/fileInput/css/fileinput.css" media="all" rel="stylesheet" type="text/css" />
<!doctype html>
<html>
<head>
<style type="text/css">
	.ibox-content{
		border: none;
	}
	
	.progress {
   	 	margin-top: 15px!important;
   	 	margin-bottom:0px;
	}
	
	.ibox-zxsearchqu {
	    padding-bottom: 5px!important;
	}
</style>
</head>
<body class="gray-bg">
	<div class="container creditbody">
		<div class="iboxtitle">
			<span><i class="glyphicon glyphicon-map-marker"></i>&nbsp;贷中业务>银行放款导入</span>
		</div>
		<div class="ibox-content ibox-zxsearchqu">
       	    <div class="uploadfile-btn">
				<form enctype="multipart/form-data">
					<input id="uploadfile" name=uploadfile type="file" onchange="upload();" class="file" data-overwrite-initial="false" data-min-file-count="1" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
				</form>
			</div>	
			<div class="uploadfile-btnb td-width">
				<select class="select-control" id="bankCode" name="bankCode">
				</select>
			</div>
			<div class="uploadfile-btnc">
				<button class="btn dpbtn_blue" type="button" onclick="previewGoods();">预览</button>
				<button class="btn dpbtn_blue" type="button" onclick="importGoods();">导入</button>
				<button class="btn dpbtn_red" type="button" onclick="previewBads();">错误数据预览</button>
				<button class="btn dpbtn_red" type="button" onclick="exportBads();">错误数据导出</button>
				<button class="btn dpbtn_green" type="button" onclick="initListTable();">显示列表</button>
			</div>
		</div>

		<div class="ibox-content">	
	          <div class="jqGrid_wrapper">
			</div>
		</div>
	</div>
	<!-- public quote -->
    <%@include file="/jsp/comm_js_include.jsp"%>

	<!-- jqGrid -->
    <script type="text/javascript" charset="utf-8" src="${basePath}/js/plugins/jqgriddemo/js/jquery.jqGrid.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="${basePath}/js/plugins/jqgriddemo/js/grid.locale-cn.min.js"></script>	
    <script src="${basePath}/js/fileInput/js/fileinput.js" type="text/javascript"></script>
    <script src="${basePath}/js/fileInput/js/locales/zh.js" type="text/javascript"></script>
    <!-- custom js -->
    <script type="text/javascript">
    var winWidth = $('div.ibox-content').width();
    var winHeight = document.body.offsetHeight - 300;
 	var win = winWidth / 7 - 20;
 	
   	var uuidKey;
    jQuery(function($) { 
    	initListTable();
    	initBankDic();
    });
   window.onresize = function() {
    	$("#table_list_1").setGridWidth($(window).width()-80);
   }
   
   function upload(){
	   var file = document.getElementById("uploadfile").files[0];
	   var fileName = file.name;
	   if(!fileName || fileName =='') {
		   layer.msg("请选择文件上传", {icon: 5, time: 3000});
		   return;
	   }
	   if(!fileName.endWith(".xls") && !fileName.endWith(".xlsx") && !fileName.endWith(".XLS") && !fileName.endWith(".XLSX")) {
		   file.name = '';
		   layer.msg("文件格式不对，请上传Excel文件", {icon: 5, time: 3000});
		   return;
	   }
	   var formData = new FormData();
       formData.append("uploadfile", file); 
	   $.ajax({
           url: "${basePath}/DzLendingImportListController/upload",
           type: "POST",
           data: formData,
           contentType: false,
           processData: false,
           beforeSend : function (XMLHttpRequest){	
	        	waitingDialog.show();
		   },
		   complete : function (XMLHttpRequest, textStatus) {	
				waitingDialog.hide();
		   },
           error:function(XMLHttpRequest, textStatus, errorThrown){
			  if(console){
				  console.info("error:" + XMLHttpRequest.responseText);
			  }
			  $("#uploadfile").val();
			  waitingDialog.hide();
	       },
           success: function (datas) {
        	  if(datas.flag == "100100") {
        		  waitingDialog.hide();
        		  hasImport = false;
       	   		  uuidKey = datas.result;
       	   		  $('#bankCode').val('');
       	   		  $('#bankCode').removeAttr('disabled');
       	   		  layer.msg('上传Excel成功', {icon: 6});
			  } else if(datas.flag == '100802') {
				  top.location.href = thisLoginUrl;
			  } else {
				  layer.msg(datas.message, {icon: 2});
			  }
           }
       });
   }
   
   function initBankDic(){
    	$.dpAjax({
	    	url:'${basePath}/DataDictionaryController/getEnableList',
 			data:{"parentValue":"LoanBank"},
 			success: function(datas){
				  var results = datas.result.rows;
				  var length = results.length;
				  var html = '<option value="">请选择放款银行</option>';
				  if(results && results.length > 0) {
 				      for(var i=0;i<results.length;i++){
 				          var loanBank = results[i];
 				          html += '<option value="' + loanBank.value + '">' + loanBank.name + '</option>';
 				      }
				  }
			     $("#bankCode").html(html);
              }
	    });
    }
	
	var hasImport = false;
	function importGoods(){
		if(!uuidKey || uuidKey =='') {
			layer.msg('请先导入银行放款Excel数据', {icon: 5,time:3000});
			return;
		}
		var bankCode = $('#bankCode').val();
		var bankName = $('#bankCode option:selected').text();
		if(!bankCode || bankCode == '') {
			layer.msg('请选择放款银行', {icon: 5,time:3000});
			return;
		}
		if(hasImport) {
			layer.msg('数据已经导入', {icon: 5, time:3000});
			return;
		} else {
			$.dpAjax({
		   		url:'${basePath}/DzLendingImportListController/importGoods',
		   		type:'POST',
		   		data:{uuidKey:uuidKey,bankCode:bankCode,bankName:bankName},
		   		success:function(datas)	{
		   			layer.msg('数据导入成功', {icon: 6});
		   			hasImport = true;
		   			$('#bankCode').attr('disabled','disabled');
		   			if(currentPreviewGood) {
		   				initListTable();
					} else {
						$("#table_list_1").jqGrid("setGridParam", { search: true }).trigger("reloadGrid");
					}
		   		}
		   	});
		}
	}
	
	//预览
	var currentPreviewGood = false;
	function previewGoods(){
		if(!uuidKey || uuidKey =='') {
			layer.msg('请先导入银行放款Excel数据', {icon: 5,time:3000});
			return;
		}
		currentPreviewBad = false;
		if(currentPreviewGood) {
			layer.msg('已经在预览中', {icon: 5,time:3000});
			return;
		} else {
			currentPreviewGood = true;
			initPreviewTableGood();
		}
	}
	

	//预览
	var currentPreviewBad = false;
	function previewBads(){
		if(!uuidKey || uuidKey =='') {
			layer.msg('请先导入银行放款Excel数据', {icon: 5,time:3000});
			return;
		}
		currentPreviewGood = false;
		if(currentPreviewBad) {
			layer.msg('已经在预览中', {icon: 5,time:3000});
			return;
		} else {
			currentPreviewBad = true;
			initPreviewTableBad();
		}
	}
	
	//导出错误数据
	function exportBads(){
		if(!uuidKey || uuidKey =='') {
			layer.msg('请先导入银行放款Excel数据', {icon: 5,time:3000});
			return;
		}
	   	$.dpAjax({
	   		url:'${basePath}/DzLendingImportListController/exportBads',
	   		type:'POST',
	   		data:{uuidKey:uuidKey,check:true},
	   		success:function(datas)	{
	   			//成功响应，说明没有报错，可以下载
	   			location.href='${basePath}/DzLendingImportListController/exportBads?uuidKey='+uuidKey;
	   			return;
	   		}
	   	});
	}
	
	function initDiv(){
		$('.jqGrid_wrapper').html('<table id="table_list_1"></table><div id="pager_list_1"></div>');
	}
	
	var loadCompletePreBad = false;
	function initPreviewTableBad(){
		initDiv();
	    $.jgrid.defaults.styleUI = 'Bootstrap';
		$("#table_list_1").jqGrid({
			url:'${basePath}/DzLendingImportListController/previewBads',
			datatype : "json",
			postData:{uuidKey:uuidKey},
			colNames : ['ID', '姓名','身份证','放款时间', '垫资额','按揭服务费','错误原因'],
			colModel : [ 
				 {name: 'replaceId', index: 'id', hidden:true},
	             {name: 'customerName',index: 'customerName',width: win,align: "center"},
	             {name: 'customerNo',index: 'customerNo',width: win,align: "center"},
	             {name: 'timeLending',index: 'timeLending',width: win,align: "center",sorttype : "date",formatter:function(a){
	            	 return (a && a != null) ? formateDate(a) : '';
	             }},
	             {name: 'amountLoaning',index: 'amountLoaning',width: win,align: "center",sorttype : "float",formatter:function(a){
	            	 return (a && a != null) ? showNumber(a) : '';
	             }},
	             {name: 'feeService',index: 'feeService',width: win,align: "center",sorttype : "float",formatter:function(a){
	            	 return (a && a != null) ? showNumber(a) : '';
	             }},
	             {name: 'errorReason',index: 'errorReason',width: win,align: "center",formatter:function(a){
	            	 return '<span style="color:#FC1515;">' + a + '</span>';
	             }}
	         ],
	         sortname : 'timeLending',
	         sortorder : "desc",
	           mtype : "post",
	           loadonce:true,
	           height: winHeight,
	           width:winWidth,  
	           autowidth: false,
	           shrinkToFit: false,
	           rowNum: 15,
	           rowList: [15, 30, 50],
	           viewrecords: true,
	           pager: "#pager_list_1",
	           hidegrid: false,
	           multiselect : false,
	           altRows:true,
		       altclass:'someClass',
	           multiboxonly:false,  
	           beforeSelectRow: false,
             jsonReader: {
                root: "result",
                repeatitems: true,
                id: "replaceId"
             },
	         loadComplete: function(datas){
	        	 if(!loadCompletePreBad) {
	        		   loadCompletePreBad = true;
		        	   if (datas.flag == "100100") {
		                   layer.msg("查询成功!", {icon: 6, time: 1000});
		                   return;
		               }
		         	  if(datas.flag == '100802') {
		 				  top.location.href = thisLoginUrl;
		 				  return;
		 			  }
		         	  
		         	  layer.msg(datas.message, {icon: 2});
	        	 }
	          }
      });
	}
	
	var loadCompletePreGood = false;
	function initPreviewTableGood(){
		initDiv();
	    $.jgrid.defaults.styleUI = 'Bootstrap';
		$("#table_list_1").jqGrid({
			url:'${basePath}/DzLendingImportListController/previewGoods',
			datatype : "json",
			postData:{uuidKey:uuidKey},
			colNames : ['ID', '姓名','身份证','放款时间', '垫资额','按揭服务费'],
			colModel : [ 
				 {name: 'replaceId', index: 'id', hidden:true},
	             {name: 'customerName',index: 'customerName',width: win,align: "center"},
	             {name: 'customerNo',index: 'customerNo',width: win,align: "center"},
	             {name: 'timeLending',index: 'timeLending',width: win,align: "center",sorttype : "date",formatter:function(a){
	            	 return (a && a != null) ? formateDate(a) : '';
	             }},
	             {name: 'amountLoaning',index: 'amountLoaning',width: win,align: "center",sorttype : "float",formatter:function(a){
	            	 return (a && a != null) ? showNumber(a) : '';
	             }},
	             {name: 'feeService',index: 'feeService',width: win,align: "center",sorttype : "float",formatter:function(a){
	            	 return (a && a != null) ? showNumber(a) : '';
	             }}
	         ],
	         sortname : 'timeLending',
	         sortorder : "desc",
	           mtype : "post",
	           loadonce:true,
	           height: winHeight,
	           autowidth: false,
	           width:winWidth,  
	           shrinkToFit: false,
	           rowNum: 15,
	           rowList: [15, 30, 50],
	           viewrecords: true,
	           pager: "#pager_list_1",
	           hidegrid: false,
	           multiselect : false,
	           altRows:true,
		       altclass:'someClass',
	           multiboxonly:false,  
	           beforeSelectRow: false,
             jsonReader: {
                root: "result",
                repeatitems: true,
                id: "replaceId"
             },
	         loadComplete: function(datas){
	        	 if(!loadCompletePreGood) {
	        		 loadCompletePreGood = true;
		        	   if (datas.flag == "100100") {
		                   layer.msg("查询成功!", {icon: 6, time: 1000});
		                   return;
		               }
		         	  if(datas.flag == '100802') {
		 				  top.location.href = thisLoginUrl;
		 				  return;
		 			  }
		         	  
		         	  layer.msg(datas.message, {icon: 2});
	        	 }
	          }
      });
	}
	
	function initListTable(){
		currentPreviewGood = false;
		loadCompletePreGood = false;
		currentPreviewBad = false;
		loadCompletePreBad  = false;
		initDiv();
	    $.jgrid.defaults.styleUI = 'Bootstrap';
		$("#table_list_1").jqGrid({
			url:'${basePath}/DzLendingImportListController/list',
	       	datatype : "json",
	       	postData:{},
		    colNames : ['ID', '姓名','身份证','放款时间', '垫资额','按揭服务费','导入时间'],
		    colModel : [ 
				 {name: 'replaceId', index: 'id', hidden:true},
	             {name: 'customerName',index: 'customerName',width: win,align: "center"},
	             {name: 'customerNo',index: 'customerNo',width: win,align: "center"},
	             {name: 'timeLending',index: 'timeLending',width: win,align: "center",formatter:function(a){
	            	 return (a && a != null) ? formateDate(a) : '';
	             }},
	             {name: 'amountLoaning',index: 'amountLoaning',width: win,align: "center",formatter:function(a){
	            	 return (a && a != null) ? showNumber(a) : '';
	             }},
	             {name: 'feeService',index: 'feeService',width: win,align: "center",formatter:function(a){
	            	 return (a && a != null) ? showNumber(a) : '';
	             }},
	             {name: 'modified', index: 'modified', width: win,align: "center",formatter:function(a){
	            	 return (a && a != null) ? formateIntegerDate(a) : '';
	             }}
	       ],
           sortname : 'modified',
           sortorder : "desc",
           mtype : "post",
           height: winHeight,
           width:winWidth,  
           autowidth: false,
           shrinkToFit: false,
           rowNum: 15,
           rowList: [15, 30, 50],
           viewrecords: true,
           pager: "#pager_list_1",
           hidegrid: false,
           multiselect : false,
           altRows:true,
	       altclass:'someClass',
           multiboxonly:false,  
           beforeSelectRow: false,
           loadComplete: function(datas){
        	   if (datas.flag == "100100") {
                   layer.msg("查询成功!", {icon: 6, time: 1000});
                   return;
               }
         	  if(datas.flag == '100802') {
 				  top.location.href = thisLoginUrl;
 				  return;
 			  }

         	  layer.msg(datas.message, {icon: 2});
           },
           jsonReader: {
                root: "result.rows",
                page: "result.page",
                total: "result.total",
                records: "result.records",
                repeatitems: true,
                id: "replaceId"
           }
      });
	}
	$("#uploadfile").fileinput({
	   	 language: 'zh', //设置语言
	   	 allowedFileExtensions: ['xlsx','xls','XLSX','XLS'],//接收的文件后缀
	   	 showUpload: false, //是否显示上传按钮
	   	 showRemove : false, //显示移除按钮
	   	 showPreview : false, //是否显示预览
 	})
    </script>
</body>
</html>
